<template>
  <div class="browser-agent">
    <div class="agent-header">
      <div class="agent-title">浏览器自动化智能体</div>
      <el-button
        type="primary"
        size="small"
        @click="showTaskDialog = true"
      >
        新建任务
      </el-button>
    </div>

    <div class="task-list">
      <el-table :data="tasks" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="任务名称" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                size="small"
                :type="row.status === 'running' ? 'danger' : 'primary'"
                :disabled="row.status === 'completed'"
                @click="handleTaskAction(row)"
              >
                {{ row.status === 'running' ? '停止' : '运行' }}
              </el-button>
              <el-button
                size="small"
                type="info"
                @click="handleViewLogs(row)"
              >
                日志
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新建任务对话框 -->
    <el-dialog
      v-model="showTaskDialog"
      title="新建自动化任务"
      width="600px"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="100px"
      >
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        <el-form-item label="任务类型" prop="type">
          <el-select v-model="taskForm.type" placeholder="请选择任务类型">
            <el-option label="网页操作" value="web" />
            <el-option label="表单填写" value="form" />
            <el-option label="数据采集" value="scraping" />
            <el-option label="自定义脚本" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标URL" prop="url">
          <el-input v-model="taskForm.url" placeholder="请输入目标网页URL" />
        </el-form-item>
        <el-form-item label="AI模型" prop="model">
          <el-select v-model="taskForm.model" placeholder="请选择AI模型">
            <el-option label="GPT-4" value="gpt-4" />
            <el-option label="GPT-3.5" value="gpt-3.5-turbo" />
            <el-option label="Claude" value="claude" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="taskForm.type === 'custom'"
          label="自定义脚本"
          prop="script"
        >
          <el-input
            v-model="taskForm.script"
            type="textarea"
            :rows="6"
            placeholder="请输入自定义Python脚本"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTaskDialog = false">取消</el-button>
          <el-button
            type="primary"
            :loading="creating"
            @click="handleCreateTask"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 任务日志对话框 -->
    <el-dialog
      v-model="showLogsDialog"
      title="任务日志"
      width="800px"
    >
      <div class="task-logs">
        <div
          v-for="(log, index) in taskLogs"
          :key="index"
          class="log-item"
          :class="log.level"
        >
          <span class="log-time">{{ formatTime(log.timestamp) }}</span>
          <span class="log-level">{{ log.level.toUpperCase() }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const tasks = ref([])
const showTaskDialog = ref(false)
const showLogsDialog = ref(false)
const creating = ref(false)
const taskLogs = ref([])

const taskForm = ref({
  name: '',
  description: '',
  type: '',
  url: '',
  model: '',
  script: ''
})

const taskRules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入任务描述', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择任务类型', trigger: 'change' }
  ],
  url: [
    { required: true, message: '请输入目标网页URL', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请选择AI模型', trigger: 'change' }
  ],
  script: [
    { required: true, message: '请输入自定义脚本', trigger: 'blur' }
  ]
}

const taskFormRef = ref(null)

// 获取任务列表
const loadTasks = async () => {
  try {
    const response = await fetch('http://localhost:8000/api/automation/tasks', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error('获取任务列表失败')
    }
    
    const data = await response.json()
    tasks.value = data
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error(error.message || '获取任务列表失败')
  }
}

// 创建新任务
const handleCreateTask = async () => {
  if (!taskFormRef.value) return
  
  await taskFormRef.value.validate(async (valid) => {
    if (valid) {
      creating.value = true
      try {
        const response = await fetch('http://localhost:8000/api/automation/tasks', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify(taskForm.value)
        })
        
        if (!response.ok) {
          throw new Error('创建任务失败')
        }
        
        showTaskDialog.value = false
        ElMessage.success('创建任务成功')
        await loadTasks()
      } catch (error) {
        console.error('创建任务失败:', error)
        ElMessage.error(error.message || '创建任务失败')
      } finally {
        creating.value = false
      }
    }
  })
}

// 运行/停止任务
const handleTaskAction = async (task) => {
  try {
    const action = task.status === 'running' ? 'stop' : 'start'
    const response = await fetch(`http://localhost:8000/api/automation/tasks/${task.id}/${action}`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`${action === 'start' ? '运行' : '停止'}任务失败`)
    }
    
    ElMessage.success(`${action === 'start' ? '运行' : '停止'}任务成功`)
    await loadTasks()
  } catch (error) {
    console.error(`${action === 'start' ? '运行' : '停止'}任务失败:`, error)
    ElMessage.error(error.message || `${action === 'start' ? '运行' : '停止'}任务失败`)
  }
}

// 查看任务日志
const handleViewLogs = async (task) => {
  try {
    const response = await fetch(`http://localhost:8000/api/automation/tasks/${task.id}/logs`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error('获取任务日志失败')
    }
    
    const data = await response.json()
    taskLogs.value = data
    showLogsDialog.value = true
  } catch (error) {
    console.error('获取任务日志失败:', error)
    ElMessage.error(error.message || '获取任务日志失败')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'info',
    running: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '等待中',
    running: '运行中',
    completed: '已完成',
    failed: '失败'
  }
  return texts[status] || status
}

onMounted(() => {
  loadTasks()
})
</script>

<style lang="scss" scoped>
.browser-agent {
  padding: 20px;
  
  .agent-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .agent-title {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .task-list {
    margin-bottom: 20px;
  }
}

.task-logs {
  max-height: 400px;
  overflow-y: auto;
  font-family: monospace;
  
  .log-item {
    padding: 4px 8px;
    border-bottom: 1px solid #eee;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.info {
      color: #409EFF;
    }
    
    &.warning {
      color: #E6A23C;
    }
    
    &.error {
      color: #F56C6C;
    }
    
    .log-time {
      margin-right: 8px;
      color: #909399;
    }
    
    .log-level {
      margin-right: 8px;
      font-weight: bold;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 